| python |
|---|
| def decorator(func): def wrapper(): print("Before function call") func() print("After function call") return wrapper @decorator def say_hello(): print("Hello") say_hello() |
| python |
|---|
| class MyContextManager: def __enter__(self): print("Entering the context") return self def __exit__(self, exc_type, exc_value, traceback): print("Exiting the context") with MyContextManager(): print("Inside the context") |
| python |
|---|
| class Meta(type): def __new__(cls, name, bases, dct): dct['custom_attr'] = 'Hello from Meta' return super().__new__(cls, name, bases, dct) class MyClass(metaclass=Meta): pass obj = MyClass() print(obj.custom_attr) |
| python |
|---|
| def count_up_to(max): count = 1 while count <= max: yield count count += 1 counter = count_up_to(5) for num in counter: print(num) |
| python |
|---|
| import threading def print_numbers(): for i in range(5): print(i) thread = threading.Thread (target=print_numbers) thread.start() thread.join() # Wait for thread to finish |
| python |
|---|
| mport multiprocessing def print_numbers(): for i in range(5): print(i) process = multiprocessing. Process(target= print_numbers) process.start() process.join() # Wait for process to finish |
| python |
|---|
| import asyncio async def fetch_data(): print("Fetching data...") await asyncio.sleep(2) print("Data fetched!") async def main(): await fetch_data() asyncio.run(main()) |
| python |
|---|
| def greet(name: str) -> str: return f"Hello, {name}" greeting = greet("Alice") print(greeting) |
| python |
|---|
| from functools import reduce numbers = [1, 2, 3, 4, 5] total = reduce(lambda x, y: x + y, numbers) print(total) |
| python |
|---|
| from collections import Counter words = ["apple", "banana", "apple", "cherry"] count = Counter(words) print(count) |
| python |
|---|
| class Singleton: _instance = None def __new__(cls): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance obj1 = Singleton() obj2 = Singleton() print(obj1 is obj2) # True |